#-*- coding: utf-8 -*-

#from xml.etree import ElementTree
#import gdata
#import atom
#import getopt
#import sys
#import string
#import time
import os
import wx
import wx.aui
import wx.lib.flatnotebook as fn
import tea as tea
from binascii import b2a_hex, a2b_hex
import imageToolbar
from formlogin import FormLogin
from panelcalendar import PanelCalendar
from calendarlist import CalendarList
from statusmain import StatusMain
from paneldays import PanelDays
import gdata.calendar.service
from functions import rfc3339


idFileExit = wx.NewId()

key = 'daniellovesfairy'

class FormMain(wx.Frame):
    bRemAccount = False
    bRemPasswd = False
    bAutoLogin = False
    calendars = []
    calevents = dict()

    def __init__(self, title, pos = wx.DefaultPosition, size = (720, 560)):
        wx.Frame.__init__(self, None, -1, title, pos, size)
        self.SetMinSize((720, 560))
        self.Hide()
        self.Center()

        #---------------------------------------
        #load configuration file
        self.conf = wx.FileConfig('Google Calendar', '',
            os.getcwd()+'/config.dat', '', wx.CONFIG_USE_LOCAL_FILE);
        wx.ConfigBase.Set(self.conf)
        #---------------------------------------
        #show login from
        formLogin = FormLogin(wx.GetTranslation('Google Calendar Login'))
        formLogin.formMain = self
        self.bRemAccount = self.conf.ReadBool('/login/rememberaccount', False)
        self.bRemPasswd = self.conf.ReadBool('/login/rememberpassword', False)
        self.bAutoLogin = self.conf.ReadBool('/login/autologin', False)
        formLogin.SetCheckboxes(
            self.bRemAccount,
            self.bRemPasswd,
            self.bAutoLogin)
        if self.bRemAccount:
            formLogin.SetAccount(self.conf.Read('/login/account'))
        if self.bRemPasswd:
            formLogin.sPasswd = tea.decrypt(
                a2b_hex(self.conf.Read('/login/password')),key)
            formLogin.SetPasswd(self.conf.Read('/login/password'))
            formLogin.editPasswd.Bind(wx.EVT_TEXT, formLogin.OnPasswdChanged)
        if self.bAutoLogin:
            formLogin.AutoLogin()

        self.GoogleCalendar = formLogin.GoogleCalendar
        login = formLogin.ShowModal()


        if self.GoogleCalendar._GetAuthToken() != None:
            #---------------------------------------
            #write login configuration
            self.conf.WriteBool('/login/rememberaccount', self.bRemAccount)
            if self.bRemAccount:
                self.conf.Write('/login/account', self.GoogleCalendar.email)
            else:
                self.conf.Write('/login/account', '')
            self.conf.WriteBool('/login/rememberpassword', self.bRemPasswd)
            if self.bRemPasswd:
                self.conf.Write('/login/password',
                    b2a_hex(tea.encrypt(
                        self.GoogleCalendar.password.encode('latin-1'), key)))
            else:
                self.conf.Write('/login/password', '')
            self.conf.WriteBool('/login/autologin', self.bAutoLogin)

            self.Show()
        else:
            self.Close()

        self.auiMgr = wx.aui.AuiManager()
        self.auiMgr.SetManagedWindow(self)

        menubar = wx.MenuBar()

        menuFile = wx.Menu()
        menuFile.Append(idFileExit, wx.GetTranslation('E&xit'))
        menubar.Append(menuFile, wx.GetTranslation('&File'))
        self.SetMenuBar(menubar)

        self.status = StatusMain(self)
        self.SetStatusBar(self.status)

        self.toolbar = wx.ToolBar(self, -1, style=
            wx.TB_HORIZONTAL | wx.NO_BORDER | wx.TB_FLAT |
            wx.TB_HORZ_TEXT | wx.TB_NODIVIDER)
        self.toolbar.SetToolBitmapSize((24, 24))
        self.toolbar.DoAddTool(idFileExit, 'Login', imageToolbar.getLoginBitmap())
        self.toolbar.AddSeparator()
        self.toolbar.AddTool(idFileExit, imageToolbar.getLoginBitmap())
        self.toolbar.AddTool(idFileExit, imageToolbar.getLoginBitmap())
        self.toolbar.AddTool(idFileExit, imageToolbar.getLoginBitmap())
        self.toolbar.AddSeparator()
        self.toolbar.AddTool(idFileExit, imageToolbar.getLoginBitmap())

#        self.SetToolBar(self.toolbar)
        self.toolbar.Realize()

        self.calendar = PanelCalendar(self)
        self.calendarList = fn.FlatNotebook(self, style = fn.FNB_NO_X_BUTTON | fn.FNB_NODRAG)

        self.personalCalendarList = CalendarList(self);
        self.favoritCalendarList = CalendarList(self);

        self.calendarList.AddPage(self.personalCalendarList, wx.GetTranslation('Personal'), True)
        self.calendarList.AddPage(self.favoritCalendarList, wx.GetTranslation('Favorit'), False)
        self.calendarList.AddPage(wx.Panel(self), wx.GetTranslation('Search'), False)


        self.calendarMain = fn.FlatNotebook(self, style = fn.FNB_VC8 | fn.FNB_NO_X_BUTTON | fn.FNB_NODRAG)
        
        self.evtPanelDaily = PanelDays(self, calevents = self.calevents)
        self.evtPanelWeekly = PanelDays(self, calevents = self.calevents)
        self.evtPanelCustomize = PanelDays(self, calevents = self.calevents)
        
        self.calendarMain.AddPage(self.evtPanelDaily, wx.GetTranslation('Daily'), True)
        self.calendarMain.AddPage(self.evtPanelWeekly, wx.GetTranslation('Weekly'), False)
        self.calendarMain.AddPage(wx.Panel(self), wx.GetTranslation('Monthly'), False)
        self.calendarMain.AddPage(self.evtPanelCustomize, wx.GetTranslation('Customize'), False)

        self.auiMgr.AddPane(self.toolbar, wx.aui.AuiPaneInfo().ToolbarPane().Top().LeftDockable(False).BottomDockable(False).RightDockable(False).Floatable(False).Resizable(False).CloseButton(False))
        self.auiMgr.AddPane(self.calendar, wx.aui.AuiPaneInfo().Position(0).Caption(wx.GetTranslation('Monthly Calendar')).MaxSize((190, 145)).Fixed().Floatable(False).CloseButton(False))
        self.auiMgr.AddPane(self.calendarList, wx.aui.AuiPaneInfo().
            Position(1).Caption(wx.GetTranslation('Calendar List')).CloseButton(False).Floatable(False))

        self.auiMgr.AddPane(self.calendarMain, wx.aui.AuiPaneInfo().CenterPane().Floatable(False).CloseButton(False))

        self.auiMgr.Update()
        
        #---------------------------------------
        #event
        self.Bind(wx.EVT_MENU, self.OnFileExit, id = idFileExit)
        self.eventFatched = False
        self.Bind(wx.EVT_SIZE, self.OnCreate)

#        self.calendar.Bind(wx.evt, self.OnSize)
        self.calendar.Bind(wx.EVT_BUTTON, self.OnShowDetails, id = self.calendar.idShowDetails)

    def OnFileExit(self, event):
        self.GetEvents('2006-01-01', '2007-06-01')
#        self.Close()
        i = self.personalCalendarList.GetSelection();
        url = self.calendarList.GetPage(self.calendarList.GetSelection()).calendars[i][1].link[0].href;
        events = self.GoogleCalendar.Query(url);
        for an_event in enumerate(events.entry):
            title = an_event[1].title.text
            if title != None:
                wx.MessageBox(title)

    def OnCreate(self, event):
        if not self.eventFatched:
            self.eventFatched = True
            feed = self.GoogleCalendar.GetCalendarListFeed()
            step = 100/len(feed.entry)
            progress = 0
            self.status.progress.Show(True)
            for i, a_calendar in enumerate(feed.entry):
                url = a_calendar.link[0].href
                events = self.GoogleCalendar.Query(url)
                all_events = []
                for j, an_event in enumerate(events.entry):
                    all_events.append(an_event)
                    if a_calendar.access_level.value == 'owner':
                        date = rfc3339.ToDate(an_event.extension_elements[5].attributes['startTime'])
                        if self.calevents.has_key(date):
                            self.calevents[date].append({'col': a_calendar.color.value, 'evt':an_event})
                        else:
                            self.calevents[date] = [{'col': a_calendar.color.value, 'evt':an_event}]
                self.calendars.append([a_calendar, all_events])
                progress += step
                self.status.progress.SetValue(progress)
                self.status.progress.Refresh()
            self.ShowCalendarList()
            self.status.progress.SetValue(0)
            self.status.progress.Show(False)
        event.Skip()
        self.ShowDetails()

    def OnShowDetails(self, event):
        self.ShowDetails()

    def ShowDetails(self):
        if len(self.calendar.days.rangeCells) == 0:
            self.evtPanelDaily._pnldays.SetDates([self.calendar.date])
        else:
            for cell in self.calendar.days.rangeCells:
                i = cell[0] * 7 + cell[1]
                print self.calendar.daystable.days[i]

    def ShowCalendarList(self):
        self.personalCalendarList.calendars= []
        self.favoritCalendarList.calendars= []
        
        for i in range(0, len(self.calendars)):
            cal = self.calendars[i]
            if cal[0].access_level.value == 'owner':
                self.personalCalendarList.calendars.append([i, cal, True])
            else:
                self.favoritCalendarList.calendars.append([i, cal, True])

        self.personalCalendarList.Reset()
        self.favoritCalendarList.Reset()

if __name__ == '__main__':
    app = wx.PySimpleApp()
    local = wx.Locale()
    local.AddCatalogLookupPathPrefix('../languages')
    local.Init(wx.LANGUAGE_CHINESE_SIMPLIFIED)
    local.AddCatalog('main')
    form = FormMain('test')
    form.Show()
    app.MainLoop()
